package com.wutong.eams.controller;

import com.wutong.eams.dto.StudentManagerDTO;
import com.wutong.eams.entity.Student;
import com.wutong.eams.entity.StudentInfo;
import com.wutong.eams.enums.RequestMethod;
import com.wutong.eams.enums.Role;
import com.wutong.eams.other.ConditionBuilder;
import com.wutong.eams.service.StudentManagerService;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/api/students/*")
public class StudentManagerController extends BaseController {

    private final StudentManagerService studentService = new StudentManagerService();

    @Override
    public Role getPermission() {
        return Role.TEACHER;
    }

    @Override
    public boolean needPermission() {
        return true;
    }

    @Override
    protected void routerHandle() {
        getRouter().addHandler("/students", RequestMethod.GET.getValue(), "text/html;charset=UTF-8", "/page/students", httpServletMethod -> {
            HttpServletRequest request = httpServletMethod.getRequest();
            HttpServletResponse response = httpServletMethod.getResponse();

            // 设置当前页面为第一页
            int currentPage = 1;
            int size = 10;
            int totalCount = getStudentManagerService().count(ConditionBuilder.NONE_CONDITION);
            int totalPages = (int) Math.ceil((double) totalCount / size);


            // 获取学生列表
            List<StudentInfo> students = getStudentManagerService().getAllStudentsWithPage(new StudentManagerDTO.QueryAllStudentsWithPageDTO(currentPage, size)).getResult();
            request.getSession().setAttribute("studentList", students);

            // 返回分页配置
            request.getSession().setAttribute("currentPage", currentPage);
            request.getSession().setAttribute("size", size);
            request.getSession().setAttribute("totalCount", totalCount);
            request.getSession().setAttribute("totalPages", totalPages);
            return null;
        });
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            StudentManagerDTO.AddStudentDTO addDTO = parseJsonRequest(req, StudentManagerDTO.AddStudentDTO.class);
            boolean success = studentService.addStudent(addDTO);
            sendJsonResponse(resp, success ? HttpServletResponse.SC_CREATED : HttpServletResponse.SC_BAD_REQUEST,
                    success ? "学生添加成功" : "学生添加失败");
        } catch (Exception e) {
            sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器错误");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String classId = req.getParameter("classId");

        try {
            if (id != null) {
                // 获取单个学生详情
                Student student = studentService.getMapper().selectOne(
                        new ConditionBuilder().where("student_id", ConditionBuilder.Operator.EQUAL, id));
                sendJsonResponse(resp, HttpServletResponse.SC_OK, student);
            } else if (classId != null) {
                // 按班级查询学生
                List<StudentInfo> students = studentService.queryStudentsByCondition(
                        new StudentManagerDTO.QueryStudentsByConditionDTO(Integer.parseInt(classId), null, null, 1, 100)).getResult();
                sendJsonResponse(resp, HttpServletResponse.SC_OK, students);
            } else {
                // 获取所有学生(分页)
                List<StudentInfo> students = studentService.getAllStudentsWithPage(
                        new StudentManagerDTO.QueryAllStudentsWithPageDTO(1, 20)).getResult();
                sendJsonResponse(resp, HttpServletResponse.SC_OK, students);
            }
        } catch (Exception e) {
            sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "查询失败");
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String id = req.getParameter("id");
            if (id == null) {
                sendErrorResponse(resp, HttpServletResponse.SC_BAD_REQUEST, "缺少学生ID");
                return;
            }

            StudentManagerDTO.UpdateStudentDTO updateDTO = parseJsonRequest(req, StudentManagerDTO.UpdateStudentDTO.class);
            boolean success = studentService.updateStudent(updateDTO);
            sendJsonResponse(resp, success ? HttpServletResponse.SC_OK : HttpServletResponse.SC_BAD_REQUEST,
                    success ? "更新成功" : "更新失败");
        } catch (Exception e) {
            sendErrorResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "更新失败");
        }
    }
}
